package com.r_z.util;


import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 订单号生成方法
 */
public class NumberUtil {

    /**
     * 获取最大编号
     * @param fieldName  编号字段名
     * @param tableName   表名
     * @param prefix  前缀  订单 “O” 销售 "S"  库存 “C”
     * @return  当天日期存在的最大编号，若是第一条 则为“O202109170001”
     */
    public static String getNumber(String fieldName,String tableName,String prefix){
        String number = null;//返回的编号
        PreparedStatement pst = null;
        Date today=new Date();
        DateFormat df = new SimpleDateFormat("yyyyMMdd");
        String birthday = df.format(today);//得到当天日期转成字符串

        try {
            //AS id别名 可以直接改
            String sql="select MAX(" + fieldName + ") AS id from " + tableName + "  where " + fieldName + " LIKE " + "'%"+prefix+birthday+"%'";
            pst = OrcleUtil.getCon().prepareStatement(sql);
            ResultSet res = pst.executeQuery();
            if (res.next()) {
                number = res.getString("id");
                if (number==null){
                    DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
                    String strDate = dateFormat.format(today);
                    number = prefix + strDate +"001";//O202109160001
                }else {
                    String strNum = number.substring(prefix.length());
                    Long num = Long.valueOf(strNum) + 1;
                    number = prefix + num;
                }
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return number;
    }

    public static void main(String[] args) {
        String number = getNumber("theMarketId", "theMarket", "TH");
        //String number = getNumber("fundCode", "fund", "TH");
        System.out.println(number);

    }

}
